.PHONY: build test clean docker-build docker-up docker-down proto-gen lint

# 项目配置
PROJECT_NAME := yanxue_ai_go
DOCKER_REGISTRY := localhost:5000
VERSION := latest

# Go配置
GO_VERSION := 1.24.7
GO_BUILD_FLAGS := -ldflags="-w -s"

# 服务列表
SERVICES := gateway agent mcp rag

# 构建所有服务
build: 
	@echo "构建所有服务..."
	@for service in $(SERVICES); do \
		echo "构建 $$service 服务..."; \
		cd services/$$service && go build $(GO_BUILD_FLAGS) -o ../../bin/$$service ./cmd/main.go && cd ../..; \
	done

# 运行测试
test:
	@echo "运行测试..."
	go test -v ./...

# 运行基准测试
benchmark:
	@echo "运行基准测试..."
	go test -bench=. -benchmem ./...

# 清理构建文件
clean:
	@echo "清理构建文件..."
	rm -rf bin/
	rm -rf vendor/

# 生成Proto文件
proto-gen:
	@echo "生成Proto文件..."
	@for service in $(SERVICES); do \
		if [ -d "services/$$service/proto" ]; then \
			protoc --go_out=. --go-grpc_out=. services/$$service/proto/*.proto; \
		fi \
	done

# 代码检查
lint:
	@echo "运行代码检查..."
	golangci-lint run

# 格式化代码
fmt:
	@echo "格式化代码..."
	go fmt ./...

# 更新依赖
deps:
	@echo "更新依赖..."
	go mod tidy
	go mod download

# Docker相关命令
docker-build:
	@echo "构建Docker镜像..."
	@for service in $(SERVICES); do \
		docker build -t $(DOCKER_REGISTRY)/$(PROJECT_NAME)-$$service:$(VERSION) -f services/$$service/Dockerfile .; \
	done

docker-push:
	@echo "推送Docker镜像..."
	@for service in $(SERVICES); do \
		docker push $(DOCKER_REGISTRY)/$(PROJECT_NAME)-$$service:$(VERSION); \
	done

docker-up:
	@echo "启动所有服务..."
	docker-compose up -d

docker-down:
	@echo "停止所有服务..."
	docker-compose down

docker-logs:
	@echo "查看日志..."
	docker-compose logs -f

# 本地开发
dev-setup:
	@echo "设置开发环境..."
	go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
	go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
	go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
	go install github.com/air-verse/air@latest

dev-agent:
	@echo "启动Agent服务开发模式..."
	cd services/agent && air

dev-mcp:
	@echo "启动MCP服务开发模式..."
	cd services/mcp && air

dev-rag:
	@echo "启动RAG服务开发模式..."
	cd services/rag && air

dev-gateway:
	@echo "启动Gateway服务开发模式..."
	cd services/gateway && air

# 数据库迁移
migrate-up:
	@echo "执行数据库迁移..."
	migrate -path migrations -database "mysql://root:password@tcp(localhost:3306)/yanxue_ai" up

migrate-down:
	@echo "回滚数据库迁移..."
	migrate -path migrations -database "mysql://root:password@tcp(localhost:3306)/yanxue_ai" down

migrate-create:
	@echo "创建新的迁移文件..."
	@read -p "请输入迁移名称: " name; \
	migrate create -ext sql -dir migrations $$name

# 帮助
help:
	@echo "可用命令:"
	@echo "  build        - 构建所有服务"
	@echo "  test         - 运行测试"
	@echo "  clean        - 清理构建文件"
	@echo "  proto-gen    - 生成Proto文件"
	@echo "  lint         - 代码检查"
	@echo "  fmt          - 格式化代码"
	@echo "  deps         - 更新依赖"
	@echo "  docker-build - 构建Docker镜像"
	@echo "  docker-up    - 启动所有服务"
	@echo "  docker-down  - 停止所有服务"
	@echo "  dev-setup    - 设置开发环境"
	@echo "  migrate-up   - 执行数据库迁移"
	@echo "  help         - 显示帮助信息"